<?php
namespace Admin\Controller;
use Think\Controller;
use Admin\Controller\ContactController;

/**
 * 单位信息管理
 * Class nianshenController
 * @package Admin\Controller
 */
class NianshenController extends AdminController {

    /**
     * 系统管理 -> 政务公开 -> 政务分类管理 -> listview
     */
    public function index(){
        //获取搜索条件
        $filter = $this->fn_GenerateFilter();
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();

        //分页信息
        $pageNum = intval(I("post.page"));
        $pageNum = $pageNum==0?1:$pageNum;
        $page = $this->fn_GetPageInfo($where, $pageNum);
        $this->assign("page", $page);

        //搜索出单位信息
        $limit = ($page['from']-1).",".$page['num'];
        $list = M("nianshen")->where($where)->order($order)->limit($limit)->select();
        for($i=0; $i<count($list); $i++){
            $list[$i]["offset"] = $page['from']-1+$i;
        }
        $this->assign("list", $list);

        //设置搜索条件
        $this->assign("filter", $filter);
        $this->display();
    }

    /**
     * 单位信息维护 -> formview
     */
    public function detail(){
        //读取单位信息
        $dataId = I("get.id");
        $nianshen = M("nianshen")->where(array("id"=>$dataId))->find();
        $this->assign("nianshen", $nianshen);

        //获取联合审批记录
        $this->assign("lhsp", $this->fn_GetLhspList($nianshen["no"]));
        $this->assign("opinion", $this->fn_GetOpinionList());

        //查询条件
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $pageInfo = $this->fn_GetPageInfo($where);

        //页面信息
        $offset = intval(I("get.offset"));
        $nearby = $this->fn_FindNearbyItems($where, $order, $offset);
        $page = array_merge($pageInfo, $nearby);
        $this->assign("page", $page);

        // 设置上下文信息
        $context = $this->fn_GenerateContext($page);
        $this->assign("context", $context);
        $this->display();
    }

    /**
     * AJAX方法，在formview中对申请进行资格初审
     */
    public function ajax_nianshen(){

        $nsId = I("post.id");
        if(!$nsId){
            $this->error("缺少必要参数");
        }
        $trans = M();
        $trans->startTrans();   // 开启事务
        try {
            //修改年审状态
            $data = array("state"=>I("post.spzt"),"opinion"=>I("post.spyj"), "utime"=>time());
            $res = M("nianshen")->where(array("id"=>$nsId))->save($data);
            if(!$res){
                $this->error("系统错误，请稍候重试");
            }

            //创建欠缴租金记录
            $nianshen = M("nianshen n")->field("n.*, h.price, h.mprice, h.size, c.derate_type")
                ->where(array("n.id"=>$nsId))
                ->join(C("DB_PREFIX")."house h on h.name=n.house_no", "LEFT")
                ->join(C("DB_PREFIX")."contact c on c.no=n.contact_no", "LEFT")
                ->find();
            /*$res = $this->fn_GenerateCharge($nianshen);
            if(!$res){
                $this->error("系统错误，创建欠缴租金记录失败");
            }*/

            //发送审核结果通知短信
            if(I("post.spzt")=="审核通过"){ //发送短信
                $res = SmsApiController::SendMsg("5000", $nianshen['phone'], $nianshen);
                if(!$res['state']){
                    \Think\Log::write("短信发送失败：".$res['info']);
                }else{
                    \Think\Log::write("短信发送成功：".$res['phone']);
                }
            }else{
                $res = SmsApiController::SendMsg("6000", $nianshen['phone'], $nianshen);
                if(!$res['state']){
                    \Think\Log::write("短信发送失败：".$res['info']);
                }else{
                    \Think\Log::write("短信发送成功：".$res['phone']);
                }
            }
            $trans->commit();   // 提交事务
            $this->success("审核成功");
        } catch (Exception $e) {
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    private function fn_GetDerateRate($type){
        foreach (ContactController::$derate_type as $item) {
            if($type == $item[0]){
                return $item[1];
            }
        }
        return 0;
    }

    public function fn_GenerateCharge($nianshen){
        $total = $this->fn_CalContactZj($nianshen, $nianshen['dibaork'], $nianshen['state']);
        $derate_money = $total * $this->fn_GetDerateRate($nianshen['derate_type']);
        $data = array(
            "community" => $nianshen['community'],
            "house_no" => $nianshen['house_no'],
            "house_addr" => $nianshen['house_addr'],
            "contact_no" => $nianshen['contact_no'],
            "total" => $total - $derate_money,
            "derate_type" => $nianshen['derate_type'],
            "derate_money" => $derate_money,
            "no" => $nianshen['no'],
            "type" => $nianshen['type'],
            "yw_no" => $nianshen['yw_no'],
            "name" => $nianshen['name'],
            "phone" => $nianshen['phone'],
            "idno" => $nianshen['idno'],
            "dibaork" => $nianshen['dibaork'],
            "zj" => $nianshen['price'],
            "mzj" => $nianshen['mprice'],
            "year" => $nianshen['year'],
            "state_ns" => $nianshen['state'],
            "state" => "未缴",
            "cuser" => session("username"),
            "ctime" => time(),
        );
        return M("charge")->add($data);
    }

    public function fn_CalContactZj($house, $dibaork, $nsState){
        if($dibaork*13>=$house['size']){ //低保人口享受面积大于房屋面积，则不要出房租
            return $house['size']*1.1*12;
        }
        //13平米每人内按1.1元每平米的价格计算
        if($nsState=='审核通过'){
            $mzj = ($house['size']-$dibaork*13)*$house['price']/$house['size'] + $dibaork*13*1.1;
        }else{
            $mzj = ($house['size']-$dibaork*13)*$house['mprice']/$house['size'] + $dibaork*13*1.1;
        }
        return $mzj*12;
    }

    protected function fn_GetOpinionList(){
        return M("opinion")->where()->order("seq asc")->select();
    }

    protected function fn_GetLhspList($no){
        $where = array("model"=>"nianshen", "no"=>$no);
        return M("lhsp")->where($where)->order("id asc")->select();
    }

    /**
     * 单位信息维护 -> 新增
     */
    public function add(){
        if(IS_POST){    //添加公司信息
            $data = array(
                "batch_id" => I("post.batch_id"),
                "name" => I("post.name"),
                "idno" => I("post.idno"),
                "phone" => I("post.phone"),
                "house_no" => I("post.house_no"),
                "ctime" => time(),
                "cuser" => session("username"),
            );
            $dataId = M("nianshen")->add($data);
            if($dataId){
                header("Location:/admin/nianshen/detail?id=".$dataId);
            }else{
                $this->error("系统错误，创建政务分类失败");
            }
        }

        //复制信息时处理流程
        if(I("get.id") && I("get.action"=="copy")){
            $nianshen = M("nianshen")->where(array("id"=>I("get.id")))->find();
            $this->assign("nianshen", $nianshen);
        }
        $this->display();
    }

    /**
     * 合同自动补全搜索算法，通过合同编号查找(未签订状态)
     */
    public function ajax_SearchContactByNo(){
        $h = array();
        //默认是查找未签订的合同
        $where = array("state"=>"未签订", "no"=>array("like", "%".I("get.no")."%"));
        $house = M("contact")->where($where)->select();
        foreach ($house as $v){
            array_push($h, array("value"=>$v["no"], "data"=>$v));
        }
        $this->ajaxReturn(array('query'=>I("get.no"),'suggestions' => $h));
    }

    /**
     * AJAX方法，在listview中进行批量删除信息
     */
    public function ajax_del(){

        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $map["id"] = array("in", $dataIds);
        $res = M("nianshen")->where($map)->delete();
        if($res){
            $this->success("操作成功");
        }else{
            $this->error("系统错误");
        }
    }

    /**
     * AJAX方法，在formview中进行单条信息删除
     */
    public function ajax_del2(){
        //根据ID删除单位记录
        $id = I("post.id");
        $res = M("nianshen")->where(array("id" => $id))->delete();
        if(!$res){
            $this->error("系统错误");
        }

        //分页信息
        $where = $this->fn_GenerateWhereClause();
        $order = $this->fn_GenerateOrderBy();
        $total = $this->fn_GetTotalItems($where);
        if($total==0){
            $this->success(null);
        }

        //计算下一条记录的offset
        $offset = intval(I("post.offset"));
        $offset = ($offset>=$total-1)?0:$offset;

        //获取下一记录的信息
        $nextItem = $this->fn_GetInfoByOffset($offset, $where, $order);
        $this->success($nextItem["id"]); //返回下一条记录的ID
    }

    //申请重新年审
    public function ajax_ReNianShen(){
        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            $map["id"] = array("in", $dataIds);
            $res = M("nianshen")->where($map)->save(array("state"=>"审核中"));
            if(!$res){
                $this->error("系统错误");
            }

            $res = M("nianshen")->where($map)->select();
            foreach ($res as $item) {
                $prefix = substr($item['yw_no'], 0, 1);
                if($prefix=="L"){
                    $model = "lzf";
                    $apply = M("lzf")->where(array("no"=>$item['yw_no']))->find();
                }else if($prefix=="G"){
                    $apply = M("gzf")->where(array("no"=>$item['yw_no']))->find();
                    $model = "gzf";
                }else{
                    $this->error("无效的申请编号");
                }
                $data = array(
                    "spdw" => "婚姻登记处",
                    "type" => "年审",
                    "model" => "nianshen",
                    "no" => $item['no'], //这里填写年审的编号
                    "name" => $apply["name"],
                    "marriage" => $apply["marriage"],
                    "gender" => $apply["gender"],
                    "idno" => $apply["idno"],
                    "area_id" => $apply["area_id"],
                    "phone" => $apply["phone"],
                    "dibaork" => $apply["dibaork"],
                    "dibaohm" => $apply["dibaohm"],
                    "income" => $apply["income"],
                    "estate" => $apply["estate"],
                    "sqtime" => time(),
                );
                $peiou = $this->fn_GetPeiOuInfo($model, $item['no']);
                if($peiou){
                    $data['name2'] = $peiou['name'];
                    $data['idno2'] = $peiou['idno'];
                    $data['gender2'] = $peiou['gender'];
                    $data['phone2'] = $peiou['phone'];
                }
                $res = M("lhsp")->add($data);
                if(!$res){
                    $this->error("系统异常，请联系管理员");
                }
            }

            $trans->commit();   // 提交事务
            $this->success("操作成功");
        } catch (Exception $e) {
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    public function fn_GetPeiOuInfo($model, $no){
        $where = array($model."_no"=>$no, "relation"=>"配偶");
        return M($model."_family")->field("name,idno,gender,phone")->where($where)->find();
    }

    /**
     * AJAX方法，免除年审
     */
    public function ajax_NoNianShen(){
        $dataIds = I("post.info");
        if(count($dataIds)==0){
            $this->error("您还没有选中任何记录");
        }

        $trans = M();
        $trans->startTrans();   // 开启事务
        try{
            $map["id"] = array("in", $dataIds);
            $res = M("nianshen")->where($map)->save(array("state"=>"免除年审"));
            if(!$res){
                $this->error("系统错误");
            }

            $ns_nos = array();
            $res = M("nianshen")->where($map)->select();
            foreach ($res as $item) {
                $ns_nos[] = $item['no'];
            }

            $where["no"] = array("in", $ns_nos);
            $res = M("lhsp")->where($where)->delete();
            if(!$res){
                $this->error("系统错误1");
            }

            $trans->commit();   // 提交事务
            $this->success("操作成功");
        } catch (Exception $e) {
            $trans->rollback();   // 开启事务
            $this->error($e->getMessage());
        }
    }

    /**
     * AJAX方法，通过ID来修改信息
     */
    public function ajax_UpdateInfoById(){
        $data = I("post.data");
        $dataId = I("post.id");
        $res = M("nianshen")->where(array("id"=>$dataId))->save($data);
        if($res){
            $this->success("0k, 200");
        }else{
            $this->error("更新异常，请稍候再试");
        }
    }

    /**
     *  辅助方法，通过$_POST的值来生成where查询条件
     */
    private function fn_GenerateWhereClause(){
        $where = array("state"=>I("get.state"));
        if(I("request.value")){
            if(I("request.field")=="batch_id"){ //多表查询处理
                $dataIds = $this->fn_SelectBatchByName(I("request.value"));
                $where[I("request.field")] = array("in", $dataIds);
            }else{
                $where[I("request.field")] = array("like", "%".I("request.value")."%");
            }
        }
        return $where;
    }

    /**
     *  辅助方法，通过$_POST的值来生成order by子句
     */
    private function fn_GenerateOrderBy(){
        $order = "id desc";
        if(I("request.order_field") && I("request.order_sort")){
            $order = I("request.order_field") . " " . I("request.order_sort");
        }
        return $order;
    }

    /**
     *  辅助方法，通过$_POST的值来生成Filter (listview)
     */
    private function fn_GenerateFilter(){
        if(IS_POST){
            return array(
                "page" => I("post.page"),
                "field" => I("post.field"),
                "state" => I("request.state"),
                "value" => I("post.value"),
                "order_field" => I("post.order_field"),
                "order_sort" => I("post.order_sort"),
            );
        }
        return array(
            "page" => 1,
            "order_field" => "id",
            "order_sort" => "desc",
            "state" => I("request.state"),
        );
    }

    /**
     * 辅助方法，通过$_POST的值来生成Context (formvier)
     * @return array
     */
    private function fn_GenerateContext($page){
        return array(
            "id" => I("request.id"),
            "field" => I("request.field"),
            "state" => I("request.state"),
            "value" => I("request.value"),
            "order_field" => I("request.order_field"),
            "order_sort" => I("request.order_sort"),
            "page" => I("request.page"),
            "offset" => I("request.offset"),
            "index" => I("get.offset")-($page["curPage"]-1)*$page["num"]+1
        );
    }

    /**
     * 辅助方法，通过where,order,offset来查询信息
     * @param $offset
     * @param $where
     * @param $order
     * @return mixed
     */
    private function fn_GetInfoByOffset($offset, $where, $order){
        $limit = $offset.",1";
        $res =  M("nianshen")->field("id,name")->where($where)->order($order)->limit($limit)->select();
        if($res){
            return $res[0];
        }
        return array();
    }

    /**
     * 辅助方法，通过where, curpage, num来生成分页信息
     * @param $where
     * @param int $curPage
     * @param int $num
     * @return array
     */
    private function fn_GetPageInfo($where, $curPage=1, $num=15){
        $total = M("nianshen")->where($where)->count();
        $totalPage = ceil($total/$num);
        $nextPage = $curPage==$totalPage?1:($curPage+1);
        $prevPage = $curPage==1?$totalPage:($curPage-1);
        $to = $curPage*$num;
        $res = array(
            "total" => $total,
            "num" => $num,
            "from" => (($curPage-1)*$num+1),
            "to" => $to>$total?$total:$to,
            "curPage" => $curPage,
            "nextPage" => $nextPage,
            "prevPage" => $prevPage
        );
        return $res;
    }

    /**
     * 辅助方法，通过where来统计总的信息数量
     * @param array $where
     * @return mixed
     */
    public function fn_GetTotalItems($where=array()){
        return M("nianshen")->where($where)->count();
    }

    /**
     * 辅助方法，通过where, order, offset查询相邻两条数据
     * @param $where
     * @param $offset
     */
    public function fn_FindNearbyItems($where, $order, $offset){
        $total = M("nianshen")->where($where)->count();
        $prevOffset = $offset>0?$offset-1:$total-1;
        $nextOffset = $offset>=$total-1?0:$offset+1;
        $prevItem = $this->fn_GetInfoByOffset($prevOffset, $where, $order);
        $nextItem = $this->fn_GetInfoByOffset($nextOffset, $where, $order);
        return array(
            "prev" => array("id"=>$prevItem["id"],"offset"=>$prevOffset),
            "next" => array("id"=>$nextItem["id"],"offset"=>$nextOffset),
        );
    }
}